package cn.agiledata.bank.linkbank.service;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.lang.StringUtils;

import cn.agiledata.bank.linkbank.exception.LinkBankException;
import cn.agiledata.bank.linkbank.logic.FieldValidateManager;

public class FieldValidateServiceImpl implements FieldValidateService {
    private String versionErrorCode;

    private Map fieldValidateManagerMapping = new HashMap();

    public void setVersionErrorCode(String versionErrorCode) {
        this.versionErrorCode = versionErrorCode;
    }

    public void setFieldValidateManagerMapping(Map fieldValidateManagerMapping) {
        this.fieldValidateManagerMapping = fieldValidateManagerMapping;
    }

    private String[] getValidVersions() {
        String[] versions = new String[this.fieldValidateManagerMapping.size()];
        int i = 0;
        for (Iterator it = this.fieldValidateManagerMapping.entrySet()
                .iterator(); it.hasNext();) {
            Map.Entry entry = (Map.Entry) it.next();
            versions[i++] = (String) entry.getKey();
        }
        return versions;
    }

    public void validateUnsPayRequestFields(String version, Map values)
            throws LinkBankException {
        FieldValidateManager manager;
        if (StringUtils.isEmpty(version)
                || (manager = (FieldValidateManager) this.fieldValidateManagerMapping
                        .get(version)) == null) {
            // 版本号不能为空，且从映射中必须能够获取域校验管理器，否则认为版本号错误
            throw LinkBankException.getVersionInvalidException(
                    getValidVersions(), this.versionErrorCode);
        }
        manager.validateFields(values);
    }
}
